package com.aurora_manito.xiaomi.service.impl;

import com.aurora_manito.xiaomi.entity.Address;
import com.aurora_manito.xiaomi.mapper.AddressMapper;
import com.aurora_manito.xiaomi.service.AddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Aurora_Manito
 * @since 2020-05-27
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Autowired
    private AddressMapper addressMapper;
    private Map<String,Object> condition=new HashMap<>();
    @Override
    public List<Address> findByUid(Integer id) {
        //通过用户id查询地址
        condition.clear();
        condition.put("uid",id);
        List<Address> addressList=addressMapper.selectByMap(condition);
        return addressList;
    }

    @Override
    public int addAddress(Address address) {

        return addressMapper.insert(address);
    }

    @Override
    public int updatedefault(Integer userid, int addressid) {
        int num=0;
        //1.条件查询将默认地址找到
        condition.put("uid",userid);
        condition.put("level",1);
        List<Address> addressList = addressMapper.selectByMap(condition);
        //2.将所有地址为1的更新为地址为0 普通地址
        for (Address address : addressList) {
            address.setLevel(0);
           num+= addressMapper.updateById(address);
        }
        //将要更改的地址更新
        Address address=addressMapper.selectById(addressid);
        address.setLevel(1);
        num+=addressMapper.updateById(address);
        return num;
    }

    @Override
    public int deleteAddress(int id) {

        return addressMapper.deleteById(id);
    }

    @Override
    public int updateAddress(Address address) {
        return addressMapper.updateById(address);
    }
}
